package login;

import java.util.HashMap;

import org.codehaus.jettison.json.JSONObject;

import platform.AppConfig;
import protocol.ParameterType;
import protocol.ReturnCode;
import io.ClientSession;
import io.OperationResponse;

public class DLlogin {
	static String dlServerUrl = "http://connect.d.cn/open/member/info/";
	static int dlApp_id = 1191;
	static String dlAppKey = "sICNiGyq";

	public static void DLlogin(OperationResponse operationRequest,
			ClientSession session) {
		
		try {
			if (operationRequest.Parameters.size() < 2) {
				OperationResponse response = new OperationResponse(
						operationRequest.OperationCode, null, ReturnCode.No, "");
				session.SendOperationResponse(response);
			}
			String id = (String) operationRequest.Parameters
					.get(ParameterType.UserID);
			String token = (String) operationRequest.Parameters
					.get(ParameterType.UserPwd);
			String deviceID = (String) operationRequest.Parameters
					.get(ParameterType.DeviceID);
			String isGetIP = (String) operationRequest.Parameters
					.get(ParameterType.IsGetIP);
			String PhoneType=(String) operationRequest.Parameters
					.get(ParameterType.PhoneType);

			if (id.equals("zealm") && token.equals("")) {
				OperationResponse response = new OperationResponse(
						operationRequest.OperationCode, AppConfig.dicAppInfo,
						ReturnCode.GetServer, "");
				session.SendOperationResponse(response);
				return;

			}
			HashMap<String, String> dicDL = LoginDL(id, token);
			if (dicDL == null) {
				return;
			}
			id = "dl" + id;
			operationRequest.Parameters.put(ParameterType.UserID, id);
			HashMap<Short, Object> myPrams = new HashMap<Short, Object>();
			myPrams.put(ParameterType.UserID, id);
			OperationResponse responseID = new OperationResponse(
					operationRequest.OperationCode, myPrams, ReturnCode.HasID,
					"");
			session.SendOperationResponse(responseID);
			Util.sdkReceived(operationRequest, session, id, deviceID, isGetIP,"DL",PhoneType,"");

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static HashMap<String, String> LoginDL(String mid, String mToken)
			throws Exception {
		if (mToken.isEmpty()) {
			return null;
		}
		HashMap<String, String> param = new HashMap<String, String>();
		String signSource = mToken + "|" + dlAppKey;// 缁勮绛惧悕鍘熸枃
		String sign = Util.getMD5Str(signSource);// MD5鍔犲瘑绛惧悕

		String body = "app_id=" + Integer.toString(dlApp_id) + "&" + "mid="
				+ mid + "&token=" + mToken + "&sig=" + sign;
		body = new String(body.getBytes("gbk"), "utf-8");
		String result = Util.sendPost(dlServerUrl, body);// httppost鏂瑰紡璋冪敤鏈嶅姟鍣ㄦ帴鍙�
		result = new String(result.getBytes("gbk"), "utf-8");
		JSONObject token = new JSONObject(result);
		String error_code = token.optString("error_code");
		if (error_code.equals("0") && !result.isEmpty()) {

			param.put("result", result);
			return param;
		}
		return null;

	}

}
